package com.huluobo.a2107mvpimdemo.register.presenter;

import android.text.TextUtils;
import android.util.Log;

import com.huluobo.a2107mvpimdemo.App;
import com.huluobo.a2107mvpimdemo.base.BasePresenter;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

/**
 * Created by LC on 2023/9/21.
 */
public class RegisterPresenter extends BasePresenter<RegisterContract.View> implements RegisterContract.Presenter {
    @Override
    public void register(String username, String password, String rePassword) {
        if (isAttach()) {
            if (username.matches(App.REGEX_USERNAME)) {
                if (password.matches(App.REGEX_PASSWORD)) {
                    if (TextUtils.equals(password, rePassword)) {
                        getView().onStartRegister();
                        registerEaseMob(username, password);
                    } else {
                        getView().onRePasswordError();
                    }
                } else {
                    getView().onPasswordError();
                }
            } else {
                getView().onUsernameError();
            }
        }

    }

    private void registerEaseMob(String username, String password) {
        //切换线程,当前网络请求执行在子线程当中,view层调用时需要切换到主线恒
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(username, password);
                    getView().onRegisterSuccess();
                } catch (HyphenateException e) {
                    getView().onRegisterFailed(e.getMessage());
                    if (e.getErrorCode() == 203) {
                        getView().onRegisterFailed("用户已注册");
                        return;
                    }
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
